# encoding=utf-8
"""
响应对象业务校验
"""
import json
import uuid
from zc_core.util.encrypt_util import md5
from ctaxccgp.utils.login import SeleniumLogin
from scrapy.exceptions import IgnoreRequest
from zc_core.middlewares.validate import BaseValidateMiddleware
from zc_core.util.http_util import retry_request
from zc_core.dao.cookie_dao import CookieDao


class BizValidator(BaseValidateMiddleware):

    def validate_sku(self, request, response, spider):
        if not response.text:
            return retry_request(request)

        meta = request.meta
        catalog_id = meta.get('catalogId')
        supplier_id = meta.get('supplierId')
        page = meta.get('page')
        rs = json.loads(response.text)
        if not rs:
            raise IgnoreRequest('[Sku]响应数据无效：<shopId=%s, fcids=%s, pageNo=%s>' % (supplier_id, catalog_id, page))

        entities = rs.get('result', {}).get('searchWithAggs', {}).get('entities', None)
        if not entities or entities.get('empty'):
            raise IgnoreRequest('[Sku]响应商品为空：<shopId=%s, fcids=%s, pageNo=%s>' % (supplier_id, catalog_id, page))

        return response

    def validate_item(self, request, response, spider):
        if not response.text:
            return retry_request(request)

        meta = request.meta
        sku_id = meta.get('skuId')

        # 特殊处理
        # if sku_id == '33254975':
        #     raise IgnoreRequest('抛弃错误数据：[%s]' % sku_id)

        js = json.loads(response.text)
        if not js.get('success', False) or 'result' not in js:
            raise IgnoreRequest('[Item][%s]%s' % (sku_id, js.get('error', '异常1：响应结构异常')))

        result = js.get('result', {})
        if not result:
            raise IgnoreRequest('[Item][%s]下架' % sku_id)
        item = result.get('item', None)
        if not item:
            raise IgnoreRequest('[Item][%s]异常2：item不存在' % sku_id)

        skus = result.get('skus', [])
        if not skus or len(skus) == 0:
            raise IgnoreRequest('[Item][%s]异常3：skus不存在' % sku_id)

        json_data = json.loads(response.text).get('result', {})
        full_price = json_data.get('skus', [{}])[0].get('fullPrice', {})
        # if json_data.get('item', {}).get('price', None) == None and full_price.get('channelPrice', None) == None and full_price.get('agreementPrice', None) == None and full_price.get('platformPrice', None) == None:
        if full_price == None or full_price =='None':
            # 重新登录
            self.log_client = str(uuid.uuid4())
            self.acw_tc = str('{}{}'.format(self.log_client, md5(self.log_client)))
            # 清理cookie
            cookie_dao = CookieDao()
            cookie_dao.delete_cookie()
            # 发起登录
            self.launcher = SeleniumLogin()
            self.cookies = self.launcher.get_cookies()
            if not self.cookies:
                raise BaseException('登录异常...')
            self.session_id = self.cookies.get('SESSION')
            if not self.session_id:
                raise BaseException('登录失败...')

        return response

    def validate_order(self, request, response, spider):
        if response.text:
            return response
        elif response.status == 200 and not response.text:
            raise IgnoreRequest('[Order]无单：[%s]' % request.meta.get('skuId'))
        else:
            raise IgnoreRequest('[Order]响应异常：[%s]' % response)
